<template>
  <div id="Scheduling">
    <el-row>
      <el-button type="primary" size="mini" @click="isTask = true"
        >调度任务列表</el-button
      >
      <el-button type="primary" size="mini" @click="isTask = false"
        >调度执行列表</el-button
      >
    </el-row>
    <el-row class="mt10">
      <el-form
        :inline="true"
        :model="query"
        class="demo-form-inline"
        size="mini"
        ref="ruleForm"
      >
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            v-if="isTask"
            @click="
              addTitle = '添加任务';
              dialogVisible = true;
            "
            >添加作业调度任务</el-button
          >
        </el-form-item>
        <el-form-item label="作业名">
          <el-input
            v-model="query.jobName"
            placeholder="请输入作业名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            icon="el-icon-search"
            type="primary"
            @click="getList"
            >查询</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-refresh"
            @click="
              query.jobName = '';
              getList();
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-row>

    <div class="tp_box mt10">
      <el-table
        v-loading="loading"
        v-if="isTask"
        :data="tableData"
        style="width: 100%"
        size="small"
        height="calc(100vh - 280px)"
      >
        <el-table-column prop="jobName" label="作业名称"> </el-table-column>
        <el-table-column prop="num" label="作业个数"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="showEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="del(scope.row.jobId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 调度执行列表 -->
      <el-table
        v-loading="loading"
        v-else
        :data="tableData"
        style="width: 100%"
        size="small"
        height="calc(100vh - 280px)"
      >
        <el-table-column prop="jobName" label="作业名称"> </el-table-column>
        <el-table-column prop="num" label="脚本个数"> </el-table-column>
        <el-table-column label="执行状态">
          <template>
            <el-tag type="success">全部完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-view"
              size="mini"
              @click="details(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="tableData.length > 0"
        :total="total"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 调度执行详情 -->
    <el-dialog title="详情" :visible.sync="open" width="700px" append-to-body>
      <el-form
        :model="item"
        label-width="110px"
        size="mini"
        v-for="item in detailsData"
        :key="item.id"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="脚本名称：">{{
              item.scriptName
            }}</el-form-item>
            <el-form-item label="执行时间：">{{
              item.executeTime
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行状态：">{{
              item.executeResult
            }}</el-form-item>
            <el-form-item label="脚本命令：">{{ item.content }}</el-form-item>
          </el-col>
        </el-row>
        <el-row class="mt15">
          <el-col>
            <el-form-item label="执行结果：">
              <el-input
                type="textarea"
                :rows="5"
                disabled
                v-model="item.outcome"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增编辑 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="dialogVisible"
      width="50%"
      append-to-body
    >
      <el-form
        label-width="80px"
        ref="addOrEditForm"
        :model="addOrEditForm"
        size="mini"
      >
        <el-form-item
          label="作业名称"
          prop="name"
          :rules="[
            { required: true, message: '请输入任务名称', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="addOrEditForm.name"
            style="300px"
            placeholder="请输入任务名称"
          ></el-input>
        </el-form-item>

        <el-form-item
          style="margin-botton: 0px"
          label-width="20px"
          v-for="(item, index) in addOrEditForm.children"
          :key="item.key"
        >
          <el-form
            :inline="true"
            ref="abc"
            :model="addOrEditForm.children[index]"
            size="mini"
            label-position="top"
          >
            <el-form-item
              prop="scriptId"
              :label="index == 0 ? '脚本名称' : ''"
              :rules="[
                {
                  required: true,
                  message: '请选择一个脚本',
                  trigger: 'blur',
                },
              ]"
            >
              <el-select v-model="item.scriptId" placeholder="请选择脚本">
                <el-option
                  :label="ele.name"
                  :value="ele.scriptId"
                  v-for="(ele, index2) in scriptData"
                  :key="index2"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="time"
              :label="index == 0 ? '执行时间' : ''"
              :rules="[
                {
                  required: true,
                  message: '请选择执行时间',
                  trigger: 'blur',
                },
              ]"
            >
              <el-date-picker
                v-model="item.time"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="index == 0 ? ' ' : ''">
              <el-button
                :class="{ mt10: index == 0 }"
                type="primary"
                icon="el-icon-plus"
                @click="addItem"
              ></el-button>
              <el-button
                type="warning"
                icon="el-icon-minus"
                @click="subItem(index)"
              ></el-button>
            </el-form-item>
          </el-form>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('addOrEditForm')"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getScriptList_Api, //脚本列表
} from "@/api/automated/script.js";
import {
  getSchedulingList_Api,
  addScheduling_Api, //添加脚本
  delScheduling_Api, //删除
  editScheduling_Api, //编辑
  gerScheduedList_Api, //执行列表
  //详情
  getSchedulingDetail_Api,
} from "@/api/automated/Scheduling.js";
export default {
  data() {
    return {
      //搜索/分页
      query: {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
      },
      //添加或编辑任务
      addTitle: "添加任务",
      //添加或编辑表单
      addOrEditForm: {
        hostId: null,
        name: "", //作业名称
        children: [{ key: Date.now(), scriptId: "", time: "" }], //脚本任务和时间
      },
      //规则
      rules: [],
      //添加编辑弹框
      dialogVisible: false,
      //调度执行详情
      open: false,
      //详情表单
      form: {
        id: 1,
        name: "作业1",
        time: "2023-11-24 12:30:30",
        result: "执行成功",
        num: 10,
        createTime: "2023-11-24 12:30:30",
      },
      //详情数据
      detailsData: [],
      //列表loading
      loading: false,
      isTask: true, //true调度任务列表   ，false调度执行列表
      //总数
      total: 0,
      //列表数据
      tableData: [],
      //脚本数据
      scriptData: [],
    };
  },
  methods: {
    //新增一个脚本选择组
    addItem() {
      this.addOrEditForm.children.push({
        key: Date.now(),
        scriptId: "",
        time: "",
      });
      console.log(this.addOrEditForm);
    },
    //减少一个脚本选择组
    subItem(index) {
      this.addOrEditForm.children.splice(index, 1);
    },
    //删除作业
    del(id) {
      this.$confirm("此操作将永久删除该作业, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          delScheduling_Api({ id: id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //显示编辑
    showEdit(row) {
      this.addTitle = "编辑任务";
      this.dialogVisible = true;
      this.addOrEditForm.name = row.jobName;
      this.addOrEditForm.children = [];
      this.addOrEditForm.jobId = row.jobId;
      if (
        typeof row.scriptTaskEntities == "object" &&
        row.scriptTaskEntities.length != 0
      ) {
        //遍历脚本
        row.scriptTaskEntities.forEach((item, index) => {
          const tempObj = {};
          tempObj.scriptId = item.scriptId;
          tempObj.time = item.executeTime;
          this.addOrEditForm.children.push(tempObj);
        });
      }
    },
    //获取数据
    getList() {
      this.loading = true;
      if (this.isTask) {
        //调度任务列表的接口
        getSchedulingList_Api(this.query).then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.loading = false;
        });
      } else {
        //调度执行列表的接口
        gerScheduedList_Api(this.query).then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.loading = false;
        });
      }
    },
    //查看详情
    details(row) {
      this.open = true;
      getSchedulingDetail_Api({ jobId: row.jobId }).then((res) => {
        this.detailsData = res.rows;
      });
    },
    //提交
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addTitle == "添加任务") {
            addScheduling_Api(this.addOrEditForm).then((res) => {
              this.$message.success(res.msg);
              this.getList();
              this.resetForm(formName);

              this.dialogVisible = false;
            });
          } else if (this.addTitle == "编辑任务") {
            editScheduling_Api(this.addOrEditForm).then((res) => {
              this.$message.success(res.msg);
              this.getList();
              this.resetForm(formName);
              this.dialogVisible = false;
            });
          }
        } else {
          console.log("error submit1!!");
          return false;
        }
      });
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.addOrEditForm.children = [
        { key: Date.now(), scriptId: "", time: "" },
      ];
    },
    //获取脚本数据
    getScriptData() {
      getScriptList_Api({
        pageNum: 1,
        pageSize: 1000,
        scope: 2,
      }).then((res) => {
        this.scriptData = res.rows;
      });
    },
  },
  created() {
    this.addOrEditForm.hostId = this.$route.query.hostid;
    //获取脚本数据
    this.getScriptData();
    //获取列表数据
    this.getList();
  },
  watch: {
    isTask: {
      //监听isTask，变化发请求获取对应数据
      handler(newVal, oldVla) {
        this.query.pageNum = 1;
        this.getList();
      },
    },
    dialogVisible: {
      handler(newVal, oldVla) {
        if (newVal && this.addTitle == "添加任务") {
          this.addOrEditForm.name = "";
          this.addOrEditForm.children = [
            { key: Date.now(), scriptId: "", time: "" },
          ];
        }
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item:not(:first-child) {
  margin-bottom: 0px !important;
}
</style>